import { defineConfig, loadEnv } from 'vite' // 新增 loadEnv
import vue from '@vitejs/plugin-vue'
import { fileURLToPath, URL } from 'node:url'
import { nodePolyfills } from 'vite-plugin-node-polyfills'
export default defineConfig(({ mode }) => { // 接收 mode 参数
                                            // 加载环境变量（关键步骤）
  const env = loadEnv(mode, process.cwd(), 'VITE_')

  return {
    plugins: [
        vue(),
      nodePolyfills({
        include: ['buffer', 'crypto', 'stream']
      })
    ],
    resolve: {
      extensions: ['.js', '.jsx', '.ts', '.tsx', '.json', '.vue'],
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    server: {
      proxy: {
        '/api': {
          target: env.VITE_API_TARGET, // 使用加载的变量
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
          configure: (proxy) => {
            proxy.on('proxyReq', (proxyReq, req) => {
              if (req.headers.accept?.includes('text/event-stream')) {
                proxyReq.setHeader('Connection', 'keep-alive')
                proxyReq.setHeader('X-Accel-Buffering', 'no')
              }
            })
          }
        }
      }
    }
  }
})